<template>
  <div>
    <el-container>
      <el-header>
        <el-card class="header-card" shadow="always">
          <el-row style="margin-top: 10px">
            <el-page-header @back="goBack" content="老人信息页面">
            </el-page-header>
          </el-row>
        </el-card>
      </el-header>
      <el-main>
        <div class="elderDiv">
          <el-card class="box-card">
            <div class="text item">
              <el-form ref="form" :model="formData" :rules="rules" label-width="100px">
                <el-row>
                </el-row>
                <el-col :span="10">
                  <el-row :gutter="10">
                    <el-form-item label="姓名" prop="elderName">
                      <el-input v-model="formData.elderName" style="width: 100px"></el-input>
                    </el-form-item>
                  </el-row>
                  <el-row :gutter="10">
                    <el-form-item label="性别" prop="elderGender">
                      <el-select v-model="formData.elderGender" placeholder="请选择" style="width: 100px">
                        <el-option label="男" value="男"></el-option>
                        <el-option label="女" value="女"></el-option>
                        <el-option label="保密" value="保密"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-row>
                  <el-row :gutter="10">
<!--                    <el-col :span="2">-->
<!--                      <el-form-item label="年龄" prop="elderAge">-->
<!--                        <el-input v-model="formData.elderAge" placeholder="" style="width: 70px" />-->
<!--                      </el-form-item>-->
<!--                    </el-col>-->
                      <el-form-item label="状态" prop="liveStatus" >
                        <el-select v-model="formData.liveStatus" placeholder="请选择" style="width: 100px">
                          <el-option label="入住" value="已住"></el-option>
                          <el-option label="暂离" value="暂离"></el-option>
                        </el-select>
                      </el-form-item>
                  </el-row>
                  <el-row :gutter="10">
<!--                    <el-form-item label="出生日期" prop="birthDate">-->
<!--                      <el-date-picker-->
<!--                        v-model="formData.birthDate"-->
<!--                        type="date"-->
<!--                        format="yyyy-MM-dd"-->
<!--                        value-format="yyyy-MM-dd"-->
<!--                        placeholder="选择日期">-->
<!--                      </el-date-picker>-->
<!--                    </el-form-item>-->
                  </el-row>
                  <el-row :gutter="10">
                    <el-row>
                      <el-form-item label="房间" prop="roomTree">
                        <el-cascader v-model="formData.roomTree" :options="roomTree" clearable
                                     :props="{label:'name',value:'Id',children:'children' }"></el-cascader>
                      </el-form-item>
                    </el-row>
                  </el-row>
<!--                  <el-row :gutter="10">-->
<!--                    <el-form-item label="押金金额" prop="deposit">-->
<!--                      <el-input v-model="formData.deposit" placeholder="" style="width: 200px"/>-->
<!--                    </el-form-item>-->
<!--                  </el-row>-->
                  <el-row :gutter="10">
                    <el-form-item label="身份证号码" prop="identityCardNumber">
                      <el-input v-model="formData.identityCardNumber" placeholder="" style="width: 200px" />
                    </el-form-item>
                  </el-row>
                  <el-row :gutter="10">
                    <el-form-item label="紧急联系电话" prop="contactPhone">
                      <el-input v-model="formData.contactPhone" placeholder="" style="width: 200px"/>
                    </el-form-item>
                  </el-row>
                  <el-row :gutter="10">
                    <el-form-item label="家庭住址" prop="homeAddress">
                      <el-input
                        type="textarea"
                        placeholder=""
                        v-model="formData.homeAddress"
                        maxlength="200"
                        show-word-limit style="width: 300px;">
                      </el-input>
                    </el-form-item>
                  </el-row>
                  <el-row :gutter="10">
                    <el-form-item label="手术史信息" prop="hasSurgeryHistory">
                      <el-input
                        type="textarea"
                        placeholder=""
                        v-model="formData.hasSurgeryHistory"
                        maxlength="200"
                        show-word-limit>
                      </el-input>
                    </el-form-item>
                  </el-row>
                  <el-row :gutter="10">
                    <el-form-item label="疾病信息" prop="hasChronicDisease">
                      <el-input
                        type="textarea"
                        placeholder=""
                        v-model="formData.hasChronicDisease"
                        maxlength="200"
                        show-word-limit>
                      </el-input>
                    </el-form-item>
                  </el-row>
                </el-col>
                <el-col :span="14">
                  <el-row :gutter="60">
                    <el-form-item label="图片:" prop="elderImg">
                      <el-image
                        style="width: 120px; height: 160px"
                        :src="formData.elderImg">
                      </el-image><br>
                      <el-upload
                        ref="uploadImg"
                        :before-upload="beforeUpload"
                        :auto-upload="false">
                        <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
                        <el-button style="margin-left: 10px;" size="small" type="primary" @click="handleUploadImg">上传</el-button>
                      </el-upload>
                    </el-form-item>
                  </el-row>
                  <el-row :gutter="20">
                    <el-form-item label="入住日期" prop="checkInTime">
                      <el-date-picker
                        v-model="formData.checkInTime"
                        type="datetime"
                        placeholder="选择日期"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss">
                      </el-date-picker>
                    </el-form-item>
                  </el-row>
                  <el-row :gutter="20">
                    <el-form-item label="离开日期" prop="checkOutTime">
                      <el-date-picker
                        v-model="formData.checkOutTime"
                        type="datetime"
                        placeholder="选择日期"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss">
                      </el-date-picker>
                    </el-form-item>
                  </el-row>
                  <el-row :gutter="10">
                    <el-form-item label="服用的药品" prop="drugName">
                      <el-input
                        type="textarea"
                        placeholder=""
                        v-model="formData.drugName"
                        maxlength="200"
                        show-word-limit>
                      </el-input>
                    </el-form-item>
                  </el-row>
                  <el-row :gutter="10">
                    <el-form-item label="备注" prop="notes">
                      <el-input
                        type="textarea"
                        placeholder=""
                        v-model="formData.notes"
                        maxlength="200"
                        show-word-limit>
                      </el-input>
                    </el-form-item>
                  </el-row>
                  <el-row :gutter="10">
                    <el-form-item label="附件" prop="url">
                      <el-upload
                        ref="upload"
                        :before-upload="beforeUpload"
                        :auto-upload="false">
                        <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
                        <el-button style="margin-left: 10px;" size="small" type="primary" @click="handleUpload">上传</el-button>
                      </el-upload>
                      <el-button type="primary" size="mini" @click="downloadFile"><a :href="form.url">下载</a></el-button>
                    </el-form-item>
                  </el-row>
                  <el-row :gutter="10">
                    <el-form-item label="审核人员" prop="checkUserName">
                      <el-input v-model="form.checkUserName" placeholder="" style="width: 200px"/>
                    </el-form-item>
                  </el-row>
                  <el-row :gutter="40" class="button">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                  </el-row>
                </el-col>
              </el-form>
                <el-dialog title="生成服务订单" :visible.sync="selectService" center>
                <el-form :model="elderForm">
<!--                  <el-form-item label="顾客姓名:" prop="customerName" >-->
<!--                    <el-input v-model="elderForm.customerName" :style="{ width: '150px' }"></el-input>-->
<!--                  </el-form-item>-->
                  <el-form-item label="房间类型:" prop="roomPriceId" >
                    <el-select v-model="elderForm.roomPriceId" placeholder="">
                      <el-option
                        v-for="item in priceList"
                        :key="item.roomPriceId"
                        :label="item.roomName+'：'+item.roomPrice"
                        :value="item.roomPriceId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="入住时间:" >
                    <el-col :span="5">
                      <el-form-item prop="liveTime">
                        <el-date-picker type="date"
                                        format="yyyy-MM-dd"
                                        value-format="yyyy-MM-dd"
                                        placeholder="选择日期" v-model="elderForm.liveTime"></el-date-picker>
                      </el-form-item>
                    </el-col>
                  </el-form-item>
                  <el-form-item label="入住时长(按月录入):" prop="liveMonth">
                    <el-input-number v-model="elderForm.liveMonth" :min="1" :max="36" label="描述文字"></el-input-number>
                  </el-form-item>
                  <el-form-item label="服务项目(多选):" prop="projectIds" >
                    <el-select v-model="elderForm.projectIds" multiple placeholder="请选择">
                      <el-option
                        v-for="item in nurseList"
                        :key="item.nurseId"
                        :label="item.nurseName+': '+item.nursePrice"
                        :value="item.nurseId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="备注:" prop="desc" style="width: 40%">
                    <el-input
                      type="textarea"
                      placeholder="请输入内容"
                      rows="3"
                      v-model="elderForm.notes"
                      maxlength="200"
                      show-word-limit
                    >
                    </el-input>
                  </el-form-item>
                  <el-tag type="info">温馨提示：所有服务均按月收费，后续退费以实际情况为准</el-tag>
                  <el-form-item>
                    <el-button type="primary" @click="createOrder">立即创建</el-button>
                    <!--                    <el-button @click="resetForm('ruleForm')">重置</el-button>-->
                  </el-form-item>
                </el-form>
<!--                <div slot="footer" class="dialog-footer">-->
<!--                  <el-button @click="selectService = false">取 消</el-button>-->
<!--                  <el-button type="primary" @click="selectService = false">确 定</el-button>-->
<!--                </div>-->
              </el-dialog>
            </div>
          </el-card>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
  import {addElderInfo, updateElderInfo,getElderInfo,fileUpload,getElderApartment,delMinioFile} from "@/api/business/elderInfo";
  import {getApartmentRoomTree, getRoomAndProject} from "@/api/business/elderlyapartment";
  import {createOrder} from "@/api/business/order";
  export default {
    name: "elderInfo",
    props: {
      formData: {
        type: Object,
        default: () => {
          return {
            elderImg: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
          }
        }
      },
    },
    data() {
      return {
        nurseList:{},
        priceList:{},
        elderForm:{},
        // 表单校验
        rules: {
          elderName: [
            { required: true, message: "姓名不能为空", trigger: "blur" }
          ],
          elderGender:[{ required: true, message: "性别不能为空", trigger: "blur"}],
          elderAge:[{ required: true, message: "年龄不能为空", trigger: "blur"}],
          liveStatus:[{ required: true, message: "居住状态不能为空", trigger: "blur"}],
          roomTree:[{ required: true, message: "不能为空", trigger: "blur"}],
          deposit:[{required: true, message: "不能为空", trigger: "blur"}],
          contactPhone: [
            { required: true, message: "紧急电话不能为空", trigger: "blur" },
            { pattern: /^1[3|4|5|7|8][0-9]\d{8}$/, message: '手机号码格式不正确', trigger: 'blur' }
          ],
          homeAddress: [
            { required: true, message: "家庭住址不能为空", trigger: "blur" }
          ],
          identityCardNumber: [
            { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号码格式不正确', trigger: 'blur' }
          ],

        },
        selectService:false,
        formLabelWidth:'120px',
        form:{
          elderId: null,
          apartmentId: null,
          elderImg: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
          elderName: null,
          elderAge: null,
          elderGender: null,
          birthDate: null,
          checkInTime: null,
          checkOutTime: null,
          roomId: null,
          bedCode: null,
          deposit: null,
          liveStatus: null,
          identityCardNumber: null,
          contactPhone: null,
          homeAddress: null,
          healthStatus: null,
          hasSurgeryHistory: null,
          hasChronicDisease: null,
          hasMentalIllness: null,
          hasInfectiousDisease: null,
          checkUserId: null,
          isUnusual: null,
          url: null,
          isDelete: null,
          notes: null,
          checkUserName: null,
          createUserId: null,
          createTime: null,
          updateUserId: null,
          updateTime: null
        },
        param:{},
        apartmentList:{},
        fileList:[],
        user:{},
        roomTree:[],
      }
    },
    // this.$route.params（刷新页面后参数会丢失）
    // this.$route.query（刷新页面后参数不会丢失）
    created(){
      // this.init();
      this.getApartment();
      this.getApartmentRoomtreeList();
      this.user = this.$store.state.user;
      this.getAprtRoomAndProject();
    },
    watch: {
      // timestamp(newTimestamp) {
      //   // 当时间戳变化时，将其转换成 Date 对象并更新 pickedDate
      //   this.pickedDate = newTimestamp ? new Date(newTimestamp) : '';
      // },
    },
    methods: {
      // init(){
      //   let obj = this.$route.query || '';
      //   for (let key in obj) {
      //     if (obj[key] === null || obj[key] === undefined) {
      //       obj[key] = "";
      //     }
      //   }
      //   this.form = obj;
      //   console.log(this.form);
      // },
      getApartment(){
        getElderApartment().then(response =>{
          this.apartmentList = response.rows;
          console.log(this.apartmentList);
        })
      },
      getElderInfo(item){
        let id = item.elderId;
        getElderInfo(id).then(response => {
            this.form = response.data;
          console.log(this.form)
        })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            //处理data数据
            if (this.formData.elderId != null) {
              this.formData.updateUserId = this.user.id;
              updateElderInfo(this.formData).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                // this.getList();
                this.goBack();
              });
            } else {
              this.formData.createUserId = this.user.id;
              addElderInfo(this.formData).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                // this.getList();
                this.goBack();
              });
            }
          }
        });
      },
      beforeUpload(file) {
          // 处理上传文件之前的逻辑，例如限制文件类型和大小等
          // ...省略相关代码...
          console.log(file)
          return true; // 返回 true 以继续上传文件
        },
        handleUpload() {
          const uploadComponent = this.$refs.upload; // 引用上传组件
          const file = uploadComponent.uploadFiles[0]; // 获取选择的文件
          if (file) {
            // 构造 FormData 对象并添加文件参数
            const formData = new FormData();
            formData.append('file', file.raw); // 添加文件参数，注意使用 file.raw 获取原始文件对象
            //调用接口
            console.log(formData);
            fileUpload(formData).then(response => {
              // 处理响应结果
              this.formData.url = response;
              console.log(response)
            }).catch(error => {
              // 处理错误
              this.$modal.msgError("上传失败!");
            });
          } else {
            // 处理未选择文件的情况
            this.$modal.msgWarning("请选择文件后上传");
          }
        },
        handleUploadImg(){
          const uploadComponent = this.$refs.uploadImg; // 引用上传组件
          const file = uploadComponent.uploadFiles[0]; // 获取选择的文件
          if (file) {
            // 构造 FormData 对象并添加文件参数
            const formData = new FormData();
            formData.append('file', file.raw); // 添加文件参数，注意使用 file.raw 获取原始文件对象
            // 发送 POST 请求将文件上传到服务器
            console.log(formData);
            fileUpload(formData).then(response => {
              // 处理响应结果
              this.formData.elderImg = response;
              this.$modal.msgSuccess("上传成功");
              console.log(response)
            }).catch(error => {
              // 处理错误
              this.$modal.msgError("上传失败!");
            });
          } else {
            // 处理未选择文件的情况
            this.$modal.msgWarning("请选择文件后上传");
          }
        },
        cancel(){
          this.$emit('return-value');
      },
      goBack(){
        this.$emit('return-value');
      },
      downloadFile(){
        if(this.formData.url === ""){
          console.log(this.formData.url);
          this.$modal.msgWarning("无文件，请上传文件后下载！！！");
        }
      },
      getApartmentRoomtreeList(){
        getApartmentRoomTree().then(response => {
          this.roomTree = response.data;
          console.log(this.roomTree);
        })
      },
      getService(){
        this.selectService = true;
      },
      createOrder() {
        this.$refs["elderForm"].validate(valid => {
          if (valid) {
            let totalAmount = 0;
            this.priceList.forEach(item => {
              if (this.elderForm.roomPriceId == item.roomPriceId) {
                this.elderForm.roomPriceId = item.roomPriceId;
                this.elderForm.roomName = item.roomName;
                this.elderForm.roomType = item.roomType;
                this.elderForm.roomPrice = item.roomPrice;
                totalAmount = totalAmount + parseInt(item.roomPrice);
              }
            });
            this.nurseList.forEach(item => {
              if (this.elderForm.projectIds.includes(item.nurseId)) {
                totalAmount = totalAmount + parseInt(item.nursePrice);
              }
            });
            this.elderForm.projectIds = this.elderForm.projectIds.join(',');
            this.elderForm.totalAmount = totalAmount;
            //从from表单中获取老人姓名
            this.elderForm.customerName = this.form.elderName;
            createOrder(this.elderForm).then(response => {
              this.$modal.msgSuccess("创建成功");
              // let orderData = response.data;
              // // 触发自定义事件，并传递数值
              // this.$emit('return-value',orderData);
            });
            //表单重置
            this.elderForm = {};
            this.selectService = false;
          }
        });
      },
      getAprtRoomAndProject(){
        getRoomAndProject().then(response=>{
          this.priceList = response.price;
          this.nurseList = response.nurse;
          console.log(this.priceList)
          console.log(this.nurseList)
        })
      },

    }
  }
</script>
<style>
  .box-card {
    /*width: 1450px;*/
    background: #f2f6f4;
  }
  .button {
    text-align: center;
    padding-top: 20px;
  }
  .header-card {
    margin-top: 10px;
    background: #f2f6f1;
  }
</style>
